from PyQt5.QtCore import QThread
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import (
    QMainWindow, QWidget, QVBoxLayout, QPushButton, QLabel,
    QHBoxLayout, QMessageBox, QFileDialog
)
from PyQt5.QtCore import pyqtSlot
from core.reminder import ReminderThread
from core.schedule_manager import ScheduleService
from database.crud.user_dao import UserDAO
from database.db_session import get_db
from ui.schedule_dialog import ScheduleDialog
# from ui.schedule_dialog import ScheduleDialog
from ui.widgets.schedule_list import ScheduleListWidget
from utils.file_util import export_schedules_to_csv, import_schedules_from_csv


class MainWindow(QMainWindow):
    def __init__(self, username):
        super().__init__()
        self.setWindowTitle("个人日程管理系统")
        icon = QIcon("E:/pythonwork/personal_schedule_system/rsc/icon.jpg")
        self.setWindowIcon(icon)
        self.resize(900, 600)
        self.username = username
        try:
            db = next(get_db())
            self.user = UserDAO.get_user_by_username(db, username)
        finally:
            db.close()

        self._init_ui()
        self.load_schedule_list()
        self._init_reminder_service()

    def _init_ui(self):
        # 顶部欢迎栏
        top_layout = QHBoxLayout()
        self.welcome_label = QLabel(f"欢迎，{self.username}")
        top_layout.addWidget(self.welcome_label)

        self.add_btn = QPushButton("➕ 添加日程")
        self.add_btn.clicked.connect(self.show_add_schedule_dialog)
        top_layout.addWidget(self.add_btn)

        self.refresh_btn = QPushButton("🔄 刷新")
        self.refresh_btn.clicked.connect(self.load_schedule_list)
        top_layout.addWidget(self.refresh_btn)

        self.export_btn = QPushButton("导出日程")
        self.export_btn.clicked.connect(self.export_schedules)
        top_layout.addWidget(self.export_btn)

        self.import_btn = QPushButton("导入日程")
        self.import_btn.clicked.connect(self.import_schedules)
        top_layout.addWidget(self.import_btn)

        top_bar = QWidget()
        top_bar.setLayout(top_layout)

        # 日程列表区
        self.schedule_list = ScheduleListWidget()

        # 总布局
        main_layout = QVBoxLayout()
        main_layout.addWidget(top_bar)
        main_layout.addWidget(self.schedule_list)

        container = QWidget()
        container.setLayout(main_layout)
        self.setCentralWidget(container)

        self.setStyleSheet("""
                    /* 主窗口样式 */
                    QMainWindow {
                        background-color: qlineargradient(
                            spread:pad, x1:0, y1:0, x2:1, y2:1,
                            stop:0 #e0f7fa, stop:1 #ffffff
                        );
                        font-family: "Microsoft YaHei";
                    }

                    /* 顶部欢迎栏 */
                    QLabel#welcome_label {
                        font-size: 30px;
                        color: #333;
                        font-weight: bold;
                        padding: 10px;
                    }

                    /* 按钮统一样式 */
                    QPushButton {
                        background-color: #4CAF50;
                        color: white;
                        border: none;
                        border-radius: 6px;
                        padding: 8px 16px;
                        font-size: 9pt;
                        font-weight: bold;
                        height:35px;
                        min-width: 80px;
                    }

                    QPushButton:hover {
                        background-color: #45a049;
                    }

                    QPushButton:pressed {
                        background-color: #3e8e41;
                    }

                    /* 日程列表区域 */
                    QScrollArea {
                        border: 1px solid #ddd;
                        border-radius: 5px;
                        background: white;
                    }
                """)

        # 为欢迎标签设置对象名以便单独样式化
        self.welcome_label.setObjectName("welcome_label")

    def show_add_schedule_dialog(self):
        dialog = ScheduleDialog(user_id=self.user.id)
        if dialog.exec_():
            self.load_schedule_list()

    def load_schedule_list(self):
        try:
            db = next(get_db())
            schedules = ScheduleService.list_user_schedules(db, self.user.id)
            if not schedules:
                print("用户没有日程记录")
            self.schedule_list.load_schedules(schedules)
        except Exception as e:
            print(f"加载日程列表时发生异常: {e}")
        finally:
            db.close()

    def _init_reminder_service(self):
        # 传递 get_db 函数（不要加括号）
        self.reminder_thread = ReminderThread(get_db, self.user.id, self)
        self.reminder_thread.start()

    @pyqtSlot(object)
    def _show_reminder_dialog(self, schedule_dict):
        # 检查线程
        assert QThread.currentThread() == self.thread(), "必须在主线程调用"
        """显示弹窗（主线程安全）"""
        from ui.reminder_dialog import ReminderDialog
        dialog = ReminderDialog(schedule_dict, self)
        # 非模态
        dialog.show()

    def closeEvent(self, event):
        if hasattr(self, 'reminder_thread'):
            self.reminder_thread.stop()
            self.reminder_thread.join(timeout=1)  # 等待线程结束
        super().closeEvent(event)

    # 导出日程逻辑
    def export_schedules(self):
        try:
            db = next(get_db())
            schedules = ScheduleService.list_user_schedules(db, self.user.id)
            if not schedules:
                QMessageBox.information(self, "提示", "暂无日程可导出。")
                return

            filepath, _ = QFileDialog.getSaveFileName(self, "导出日程", "", "CSV 文件 (*.csv)")
            if not filepath:
                return

            try:
                export_schedules_to_csv(filepath, schedules)
                QMessageBox.information(self, "导出成功", f"日程已保存为：{filepath}")
            except Exception as e:
                QMessageBox.critical(self, "导出失败", str(e))
        finally:
            db.close()

    # 导入日程逻辑
    def import_schedules(self):
        filepath, _ = QFileDialog.getOpenFileName(self, "导入日程", "", "CSV 文件 (*.csv)")
        if not filepath:
            return
        try:
            db = next(get_db())
            try:
                count = import_schedules_from_csv(filepath, self.user.id, db)
                QMessageBox.information(self, "导入完成", f"成功导入 {count} 条日程。")
                self.load_schedule_list()  # 刷新列表
            except Exception as e:
                QMessageBox.critical(self, "导入失败", str(e))
        finally:
            db.close()

